<template>
  <section class="todoapp">
    <hm-header @add-event="addEvent"></hm-header>
    <hm-main
      :list="showList"
      @change-done-event="doneChange"
      @delete-event="deleteEvent"
      @change-all-event="changeAll"
    ></hm-main>
    <hm-footer
      :list="list"
      @clear-event="clearEvent"
      :status="status"
      @status-event="status = $event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/active": "undone",
  "#/completed": "done",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list:JSON.parse(localStorage.getItem("list")),
      status: obj[location.hash],
    };
  },
  methods: {
    doneChange(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list[index].done = !this.list[index].done;
    },
    deleteEvent(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    addEvent(name) {
      const id = this.list.length ? this.list.slice(-1)[0].id + 1 : 1;
      const obj = {
        id,
        name,
        done: false,
      };
      this.list.push(obj);
    },
    clearEvent() {
      this.list = this.list.filter((item) => item.done === false);
    },
    changeAll(value) {
      this.list = this.list.map((item) => {
        item.done = value;
        return item;
      });
    },
  },
  computed: {
    showList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "undone") {
        return this.list.filter((item) => item.done === false);
      } else {
        return this.list.filter((item) => item.done === true);
      }
    },
  },
  watch:{
    list:{
      handler(newValue) {
        return localStorage.setItem("list",JSON.stringify(newValue))
    }
  }
}}
</script>

<style></style>
